package app.vendorportal.web.interceptor;

import app.vendorportal.domain.permission.VendorUserActionPermissionMapping;
import app.vendorportal.service.VendorUserPermissionService;
import app.vendorportal.web.exception.PermissionForbiddenException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class VendorPermissionInterceptor extends HandlerInterceptorAdapter {

    private VendorUserPermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            String requestAction = getRequestAction(request);
            VendorUserActionPermissionMapping vendorUserActionPermissionMapping = permissionService.getVendorUserActionPermissionMapping(requestAction);
            if (null != vendorUserActionPermissionMapping && !permissionService.isCurrentVendorUserHasPermission(vendorUserActionPermissionMapping.getPermissionId())) {
                throw new PermissionForbiddenException("you are not allowed to access this page.");
            }
        }
        return true;
    }

    private String getRequestAction(HttpServletRequest request) {
        String requestAction = request.getRequestURI(); // TODO(B) request.getPathInfo();
        if (!requestAction.startsWith("/"))
            requestAction = "/" + requestAction;
        requestAction = StringUtils.replace(requestAction, request.getContextPath(), "");
        return requestAction;
    }

    @Inject
    public void setPermissionService(VendorUserPermissionService permissionService) {
        this.permissionService = permissionService;
    }
}
